/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman.business.config;

import com.mycila.xmltool.XMLDoc;
import com.mycila.xmltool.XMLTag;
import langman.util.doping.SingletonBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SingletonBean
public class ConfigService {
    private final Map<File, Config> loadedConfigs = new HashMap<>();

    public Config loadConfig(File file) {
        if (loadedConfigs.containsKey(file)) {
            return loadedConfigs.get(file);
        }

        Config config = parseConfig(file);
        loadedConfigs.put(file, config);
        return config;
    }

    private Config parseConfig(File file) {
        XMLTag xmlDoc = XMLDoc.from(file, true);

        List<SetDescription> setDescriptions = new ArrayList<>();
        Iterable<XMLTag> setTags = xmlDoc.getChilds("set");
        for (XMLTag setTag : setTags) {
            String setName = setTag.getAttribute("name");
            List<LanguageDescription> languageDescriptions = parseLanguageDescriptions(setTag);
            SetDescription setDescription = new SetDescription(setName, languageDescriptions);
            setDescriptions.add(setDescription);
        }

        return new Config(setDescriptions);
    }

    private List<LanguageDescription> parseLanguageDescriptions(XMLTag setTag) {
        List<LanguageDescription> languageDescriptions = new ArrayList<>();
        Iterable<XMLTag> languageTags = setTag.getChilds("language");
        for (XMLTag languageTag : languageTags) {
            String languageName = languageTag.getAttribute("name");
            String languageFileName = languageTag.getAttribute("file");
            boolean isReference = languageTag.hasAttribute("isReference");
            LanguageDescription languageDescription = new LanguageDescription(languageName, languageFileName, isReference);
            languageDescriptions.add(languageDescription);
        }
        return languageDescriptions;
    }

}
